<?php

require_once "db.class.php";
require_once APP_ROOT . "/Models/page.class.php";

/**
 * @author    OP
 * @since    2016-9-22
 * @desc  基本操作
 */
class main
{

    protected $loginUserInfo;

    function __construct()
    {
        $this->loginUserInfo = isset($_SESSION['q_memberInfo']) ? $_SESSION['q_memberInfo'] : '';
    }

    /**
     * 获取安全GET参数
     * @param objId
     * @param dataType 为空表示所有, int数字,data日期
     * @return string
     * */
    function _get($objId, $dataType = '')
    {
        $_tmpStr = (isset($_GET[$objId])) ? $_GET[$objId] : "";
        $_tmpStr = str_replace('\'', '', $_tmpStr);
        $_tmpStr = filter_var($_tmpStr, FILTER_SANITIZE_STRING);
        $_tmpStr = $this->getSafeData($_tmpStr);

        if ($dataType == "int") {
            if ($_tmpStr != "" && !is_numeric($_tmpStr)) {
                exit("非法请求");
            }
        }
        if ($dataType == "date") {
            if ($_tmpStr != "" && !$this->isDate($_tmpStr)) {
                exit("你提交的数据不正确");
            }
        }
        return $_tmpStr;
    }

    /**
     * 获取安全POST数据
     * @param objId  目标对象ID
     * @param dataType 为空表示所有, int数字
     * @return string
     * */
    function _post($objId, $dataType = '')
    {
        $_tmpStr = null;
        if (isset($_POST[$objId])) {
            $_tmpStr = $_POST[$objId];
        } else {
            return "";
        }
        $_tmpStr = $this->getSafeData($_tmpStr);
        if ($dataType == "int") {
            if ($_tmpStr != "" && !is_numeric($_tmpStr)) {
                sysMsg::error("你填写的数据有误,应为数字型!", array("fieldName" => $objId));
            }
        }
        if ($dataType == "date") {
            if ($_tmpStr != "" && !$this->isDate($_tmpStr)) {
                sysMsg::error("你填写的数据有误!", array("fieldName" => $objId));
            }
        }
        return $_tmpStr;
    }

    /**
     * 添加/修改数据
     * @param type $saveArr 传值模拟 array("id" => "值","tableName" => "值","list" => array("列名1" => "增加/修改值1"),array("列名2" => "增加/修改值2"))
     * @return type
     */
    static function save($saveArr)
    {
        $totalKey = "(";
        $totalTitle = "(";
        $total = "";
        foreach ($saveArr["list"] as $key => $vv) {
            if (empty($saveArr["id"])) {
                $totalKey .= "$key,";
                $totalTitle .= "'$vv',";
            } else {
                if ($key == "finishNum") {
                    $total .= "$key = $vv,";
                } else {
                    $total .= "$key = '$vv',";
                }
            }
        }
        if (empty($saveArr["id"])) {
            $tableName = $saveArr["tableName"];
            $newTotalKey = substr($totalKey, 0, (strlen($totalKey) - 1)) . ")";
            $newTotalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 1)) . ")";

            $sql = "insert into $tableName $newTotalKey values $newTotalTitle";
        } else {
            $tableName = $saveArr["tableName"];
            $id = $saveArr["id"];
            if (strstr($id, ",")) {
                $id = substr($id, 0, strlen($id) - 1);
            }
            $newTotal = substr($total, 0, (strlen($total) - 1));
            $sql = "update " . $tableName . " set " . $newTotal . " where id in ($id)";
        }
        return db::runsql($sql);
    }

    /**
     * 添加/修改数据
     * @param type $saveArr 传值模拟 array("id" => "值","tableName" => "值","list" => array("列名1" => "增加/修改值1"),array("列名2" => "增加/修改值2"))
     * @return type
     */
    static function saveAsPara($saveArr)
    {
        $totalKey = "(";
        $totalTitle = "(";
        $total = "";
        foreach ($saveArr["list"] as $key => $vv) {
            if (empty($saveArr["id"])) {
                $totalKey .= "$key,";
                if ($key == "nickname") {
                    $totalTitle .= "\"$vv\",";
                } else {
                    $totalTitle .= "'$vv',";
                }
            } else {
                if ($key == "finishNum") {
                    $total .= "$key = $vv,";
                } else if ($key == "nickname") {
                    $total .= "$key = \"$vv\",";
                } else {
                    $total .= "$key = '$vv',";
                }
            }
        }
        if (empty($saveArr["id"])) {
            $tableName = $saveArr["tableName"];
            $newTotalKey = substr($totalKey, 0, (strlen($totalKey) - 1)) . ")";
            $newTotalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 1)) . ")";

            $sql = "insert into $tableName $newTotalKey values $newTotalTitle";
        } else {
            $tableName = $saveArr["tableName"];
            $id = $saveArr["id"];
            if (strstr($id, ",")) {
                $id = substr($id, 0, strlen($id) - 1);
            }
            $newTotal = substr($total, 0, (strlen($total) - 1));
            $sql = "update " . $tableName . " set " . $newTotal . " where id in ($id)";
        }
        return db::runsql($sql);
    }

    /**
     * 添加/修改数据
     * @param type $saveArr 传值模拟 array("id" => "值","tableName" => "值","list" => array("列名1" => "增加/修改值1"),array("列名2" => "增加/修改值2"))
     * @return type
     *
     * 返回插入的ID
     */
    static function saveForId($saveArr)
    {
        $totalKey = "(";
        $totalTitle = "(";
        $total = "";
        foreach ($saveArr["list"] as $key => $vv) {
            if (empty($saveArr["id"])) {
                $totalKey .= "$key,";
                $totalTitle .= "'$vv',";
            } else {
                if ($key == "finishNum") {
                    $total .= "$key = $vv,";
                } else {
                    $total .= "$key = '$vv',";
                }
            }
        }
        if (empty($saveArr["id"])) {
            $tableName = $saveArr["tableName"];
            $newTotalKey = substr($totalKey, 0, (strlen($totalKey) - 1)) . ")";
            $newTotalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 1)) . ")";

            $sql = "insert into $tableName $newTotalKey values $newTotalTitle";
        } else {
            $tableName = $saveArr["tableName"];
            $id = $saveArr["id"];
            $newTotal = substr($total, 0, (strlen($total) - 1));

            $sql = "update " . $tableName . " set " . $newTotal . " where id in ($id)";
        }
        return db::querySql($sql);
    }

    /**
     * 添加/修改数据
     * @param type $saveArr 传值模拟 array("id" => "值","tableName" => "值","list" => array("列名1" => "增加/修改值1"),array("列名2" => "增加/修改值2"))
     * @return type
     */
    private function modify($saveArr)
    {
        $totalKey = "(";
        $totalTitle = "(";
        $list = $saveArr["list"];
        $dataBaseArray = array('setValueStart', 'setValueEnd', 'setRechargeType', 'groupId', 'createId', 'createTime');
        foreach ($list as $key => $val) {
            foreach ($dataBaseArray as $kk => $vv) {
                if ($key == 0) {
                    $totalKey .= "$vv,";
                }
                if (empty($val[$vv])) {
                    $totalTitle .= "'',";
                } else {
                    $value = $val[$vv];
                    $totalTitle .= "'$value',";
                }
            }
            $totalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 1));
            $totalTitle .= "),(";
        }

        $tableName = $saveArr["tableName"];
        $newTotalKey = substr($totalKey, 0, (strlen($totalKey) - 1)) . ")";
        $newTotalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 2));
        $sql = "insert into $tableName $newTotalKey values $newTotalTitle";

        return db::runsql($sql);
    }

    /**
     * 获取列表
     *
     * @param type $config 传值模拟 array("tableName" => "值","selectField" => "值","orderBy" => "值","pageSize" => "值","page" => "值","searchCondition" => "值","pageSize" => "值")
     * @return string
     */
    public static function getList($config)
    {
        $tableName = $config["tableName"];
        $selectField = $config['selectField']; //搜索字段
        $orderBy = $config['orderBy']; //排序方式
        $pageSize = $config['pageSize']; //每页数量
        $page = $config['page']; //页次
        $searchCondition = $config['searchCondition']; //搜索条件
        $whereStr = db::convertSearchToSql($searchCondition);
        $offSet = ($page - 1) * $pageSize;
        $_tempIdArr = db::getIds(array(
            "tableName" => $tableName,
            "selectField" => "id",
            "whereCondition" => $whereStr,
            "orderBy" => $orderBy,
            "offSet" => $offSet,
            "limitRows" => $pageSize
        ));
        $listIds = $_tempIdArr['ids']; //查询结果ID集
        $sql = $_tempIdArr['sql']; //调试用SQL

        if ($listIds == '') {
            $backArr['totalRows'] = 0;
            $backArr['currPage'] = 0;
            $backArr['pageCount'] = 0;
            $backArr['list'] = array();
            $backArr['pageStr'] = '';
            $backArr['listIds'] = '';
            return $backArr;
        }
        $totalRows = db::getCount($tableName, $whereStr);

        $listArr = db::getArr(array(
            "tableName" => $tableName,
            "selectField" => "$selectField",
            "whereCondition" => "where id in ($listIds)",
            "orderBy" => $orderBy
        ));

        $backArr['totalRows'] = intval($totalRows);
        $backArr['currentPage'] = intval($page);
        $backArr['list'] = $listArr;

        return $backArr;
    }

    /**
     * 获取列表
     *
     * @param type $config 传值模拟 array("tableName" => "值","selectField" => "值","orderBy" => "值","pageSize" => "值","page" => "值","searchCondition" => "值","pageSize" => "值")
     * @return string
     */
    public static function getListByGroup($config)
    {
        $tableName = $config["tableName"];
        $selectField = $config['selectField']; //搜索字段
        $orderBy = $config['orderBy']; //排序方式
        $groupBy = $config['groupBy']; //排序方式
        $pageSize = $config['pageSize']; //每页数量
        $page = $config['page']; //页次
        $searchCondition = $config['searchCondition']; //搜索条件
        $whereStr = db::convertSearchToSql($searchCondition);
        if($page == 1){
            $limit = 0;
        }else{
            $limit = ($page - 1) * $pageSize -1;
        }
        $_tempIdArr = db::getIds(array(
            "tableName" => $tableName,
            "selectField" => "id",
            "whereCondition" => $whereStr,
            "orderBy" => $orderBy,
//            "groupBy" => $groupBy,
            "offSet" => $limit,
//            "limitRows" => $pageSize
        ));
        $listIds = $_tempIdArr['ids']; //查询结果ID集
        $sql = $_tempIdArr['sql']; //调试用SQL

        if ($listIds == '') {
            $backArr['totalRows'] = 0;
            $backArr['currPage'] = 0;
            $backArr['pageCount'] = 0;
            $backArr['list'] = array();
            $backArr['pageStr'] = '';
            $backArr['listIds'] = '';
            return $backArr;
        }
        $listArr = db::getArr(array(
            "tableName" => $tableName,
            "selectField" => "$selectField",
            "whereCondition" => "where id in ($listIds)",
            "orderBy" => $orderBy,
            "groupBy" => $groupBy,
            "offSet" => $limit,
//            "limitRows" => $pageSize
        ));
        $count = db::getArr(array(
            "tableName" => $tableName,
            "selectField" => "$selectField",
            "whereCondition" => "where id in ($listIds)",
            "orderBy" => $orderBy,
            "groupBy" => $groupBy,
        ));
        $totalRows = count($count);
        $backArr['totalRows'] = intval($totalRows);
        $backArr['currentPage'] = intval($page);
        $backArr['list'] = $listArr;

        return $backArr;
    }

    /**
     * @param $config
     * @param null $type
     * @return mixed
     *
     * 获取例表数据
     */
    public static function getListByJoin($config, $type = null)
    {
        $tableName = $config["tableName"];
        $selectField = $config['selectField']; //搜索字段
        $orderBy = $config['orderBy']; //排序方式
        $pageSize = $config['pageSize']; //每页数量
        $page = $config['page']; //页次
        $searchCondition = $config['searchCondition']; //搜索条件
        $linkStr = $config['linkStr']; //页码自定链接，可为空
        $whereStr = db::convertSearchToSql($searchCondition);
        if ($linkStr == "") {
            $linkStr = db::convertSearchToLinkStr($linkStr);
        }
        $offSet = ($page - 1) * $pageSize;

        $_tempIdArr = db::getIds(array(
            "tableName" => $tableName,
            "selectField" => "id",
            "whereCondition" => $whereStr,
            "orderBy" => $orderBy,
            "offSet" => $offSet,
            "limitRows" => $pageSize
        ));
        $listIds = $_tempIdArr['ids']; //查询结果ID集
        $sql = $_tempIdArr['sql']; //调试用SQL

        if ($listIds == '') {
            $backArr['totalRows'] = 0;
            $backArr['currPage'] = 0;
            $backArr['pageCount'] = 0;
            $backArr['list'] = array();
            $backArr['pageStr'] = '';
            $backArr['listIds'] = '';
            return $backArr;
        }
        $totalRows = db::getCount($tableName, $whereStr);

        if ($type == 'join') {
            global $myPDO;
            $sql = "select lm.id,lm.cardNumber,lm.userPass,lm.userName,lm.sex,lm.mobile,lm.birthday,lm.head,lm.permit,lm.isMember,lm.referee,lm.balance,lm.integral,lm.qq,lm.email,lm.address,lm.remark,lm.historyIntegral,lm.historyFee,lm.`status`,lm.isDelete,lm.createTime,lm.groupId,lg.groupName from lf_member lm,lf_membergroup lg where lm.groupId = lg.id and  lm.id in ($listIds) order by lm.createTime desc";
            $listArr = $myPDO->getAll($sql);
        } else {
            $listArr = db::getArr(array(
                "tableName" => $tableName,
                "selectField" => "{$selectField}",
                "whereCondition" => "where id in($listIds)",
                "orderBy" => $orderBy
            ));
        }

        $backArr['totalRows'] = intval($totalRows);
        $backArr['currentPage'] = intval($page);
        $backArr['list'] = $listArr;

        return $backArr;
    }

    /**
     * 通过Sql语句查询列表
     *
     * @param type $sql
     * @return type
     */
    public static function getArrayBySql($sql)
    {
        return db::getArray($sql);
    }

    /**
     * 通过ID获取信息
     *
     * @param type $getArr 传值模拟 array("id" => "值","tableName" => "值","selField" => "值","isPic" => "false")
     * @return type
     */
    static function getListById($getArr)
    {
        $id = $getArr["id"];
        $tableName = $getArr["tableName"];
        $selField = $getArr["selField"] ? $getArr["selField"] : "*";

        if ($id == "" || $id == null || $id == "0") {
            return array();
        }
        $_tempInfo = db::getArr(array(
            "tableName" => $tableName,
            "selectField" => $selField,
            "whereCondition" => "where id = $id"
        ));
        return $_tempInfo;
    }

    /**
     * @param $arr
     * @return bool
     *
     * 执行多个sql语句
     */
    public function transSql($dealId, $sqlArray)
    {
        $returnArray["code"] = 0;
        $insertFirst = $sqlArray["main"];
        $insertSecond = $sqlArray["son"];
        $newInsertSecond = null;
        $i = 0;
        if (count($insertSecond["discount"]) > 0) {
            $discount = $insertSecond["discount"];
            foreach ($discount as $key => $val) {
                $newInsertSecond[$i]["setValueStart"] = $val["setValueStart"];
                $newInsertSecond[$i]["setValueEnd"] = $val["setValueEnd"];
                $i++;
            }
        }

        if (count($insertSecond["rechargeOffer"]) > 0) {
            $recharge = $insertSecond["rechargeOffer"];
            foreach ($recharge as $kk => $vv) {
                $newInsertSecond[$i]["setValueStart"] = $vv["setValueStart"];
                $newInsertSecond[$i]["setValueEnd"] = $vv["setValueEnd"];
                $newInsertSecond[$i]["setRechargeType"] = $vv["setRechargeType"];
                $i++;
            }
        }
        //执行新增的方法
        if (empty($dealId)) {
            $insertFirst["createId"] = 1;
            $insertFirst["createTime"] = date("Y-m-d H:i:s", time());
            $insertFirst["groupTurn"] = $this->getGroupTurn();
            $insertId = db::insert("lf_membergroup", $insertFirst);
            $insertTime = date("Y-m-d H:i:s", time());
            if ($insertId) {
                if (!empty($newInsertSecond)) {
                    foreach ($newInsertSecond as $kkk => $vvv) {
                        $newInsertSecond[$kkk]["groupId"] = intval($insertId);
                        $newInsertSecond[$kkk]["createId"] = 1;
                        $newInsertSecond[$kkk]["createTime"] = $insertTime;
                    }

                    $insertArr["tableName"] = "lf_base_discount";
                    $insertArr["list"] = $newInsertSecond;
                    $result = $this->modify($insertArr);
                    if ($result) {
                        $returnArray["code"] = "1";
                        $returnArray["msg"] = "新增会员等级信息成功......";
                    } else {
                        $returnArray["msg"] = "插入从表数据出错,请联系管理员......";
                    }
                }
            } else {
                $returnArray["msg"] = "新增信息失败,请稍后重试...";
            }
        } else {
            $insertTime = date("Y-m-d H:i:s", time());
            $updateArray["id"] = $dealId;
            $updateArray["tableNameForUpdate"] = "lf_membergroup";
            $updateArray["tableNameForInsert"] = "lf_base_discount";
            $updateArray["updateList"] = $insertFirst;
            if (count($newInsertSecond) > 0) {
                foreach ($newInsertSecond as $kkk => $vvv) {
                    $newInsertSecond[$kkk]["groupId"] = intval($dealId);
                    $newInsertSecond[$kkk]["createId"] = 1;
                    $newInsertSecond[$kkk]["createTime"] = $insertTime;
                }

                $updateArray["insertList"] = $newInsertSecond;
            } else {
                $updateArray["insertList"] = null;
            }

            $result = $this->operateSql($updateArray);

            if ($result) {
                $returnArray["code"] = 1;
                $returnArray["msg"] = "修改信息成功...";
            } else {
                $returnArray["msg"] = "修改信息失败,请稍后重试...";
            }
        }

        return $returnArray;
    }

    /**
     * 获取用户等级组的顺序
     */
    private function getGroupTurn()
    {
        $sqlCount = "select count(id) as countNum from lf_membergroup";
        $sqlCountList = db::getArray($sqlCount);
        return $sqlCountList[0]["countNum"] + 1;
    }

    /**
     * @param $operateArr
     * @return array|null
     *
     * 执行多条sql语句
     */
    private function operateSql($operateArr)
    {
        $tableNameForUpdate = $operateArr["tableNameForUpdate"];
        $tableNameForInsert = $operateArr["tableNameForInsert"];
        $groupId = $operateArr["id"];
        $updateList = $operateArr["updateList"];
        $insertList = $operateArr["insertList"];
        $finalSqlArr[] = "delete from lf_base_discount where groupId = $groupId";

        if (!empty($updateList)) {
            $updateSql = "update $tableNameForUpdate set ";
            foreach ($updateList as $key => $val) {
                $updateSql .= "$key = '$val',";
            }
            $updateSql = substr($updateSql, 0, (strlen($updateSql) - 1)) . " where id = $groupId";
            $finalSqlArr[] = $updateSql;
        }
        if (!empty($insertList)) {
            foreach ($insertList as $keyInsert => $valInsert) {
                $sqlFinal = "insert into $tableNameForInsert ";
                $sqlTitle = "(";
                $sqlKey = "(";
                foreach ($valInsert as $kk => $vv) {
                    $sqlTitle .= "$kk,";
                    $sqlKey .= "'$vv',";
                }
                $sqlTitle = substr($sqlTitle, 0, (strlen($sqlTitle) - 1)) . ")";
                $sqlKey = substr($sqlKey, 0, (strlen($sqlKey) - 1)) . ")";

                $finalSqlArr[] = $sqlFinal . $sqlTitle . " values " . $sqlKey;
            }
        }
        if (count($finalSqlArr) > 0) {
            global $myPDO;
            $finalResult = $myPDO->queryTransAction($finalSqlArr);
            return $finalResult;
        } else {
            return null;
        }

    }

    /**
     * @param $spiltArr
     *
     * 通过数组去整合sql语句
     */
    private function spiltSql($spiltArr)
    {
        $tableNameForUpdate = $spiltArr["tableNameForUpdate"];
        $tableNameForInsert = $spiltArr["tableNameForInsert"];
        $groupId = $spiltArr["id"];
        $totalKey = "update $tableNameForUpdate set ";
        if (empty($spiltArr["updateList"])) {

        }
        foreach ($spiltArr["updateList"] as $key => $val) {
            $totalKey .= "$key = '$val' ,";
        }
        $totalKey = substr($totalKey, 0, (strlen($totalKey) - 1)) . ")";
        $totalKey = $totalKey . " where id = $groupId" . ";";

        $totalTitle = "(";
        $totalNewKey = "insert into " . $tableNameForInsert . " ( ";

        $dataBaseArray = array('setValueStart', 'setValueEnd', 'setRechargeType', 'groupId', 'createId', 'createTime');
        foreach ($spiltArr["insertList"] as $keyInsert => $valInsert) {
            foreach ($dataBaseArray as $kk => $vv) {
                if ($keyInsert == 0) {
                    $totalNewKey .= "$vv,";
                }
                if (empty($valInsert[$vv])) {
                    $totalTitle .= "'',";
                } else {
                    $value = $valInsert[$vv];
                    $totalTitle .= "'$value',";
                }
            }
            $totalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 1));
            $totalTitle .= "),(";
        }

        $newTotalKey = substr($totalNewKey, 0, (strlen($totalNewKey) - 1));
        $newTotalTitle = substr($totalTitle, 0, (strlen($totalTitle) - 2));
        $finalSql = $totalKey . $newTotalKey . " values " . $newTotalTitle;
        $sql = "delete from lf_base_discount where groupId = $groupId";

        $transArray[] = $sql;
        $transArray[] = $finalSql;

        $finalResult = $this->transSubmit($transArray);
        return $finalResult;
    }

    /**
     * @param $sqlArr
     * @return bool
     *
     * 事物提交
     */
    private function transSubmit($sqlArr)
    {
        global $myPDO;
        return $myPDO->queryTransAction($sqlArr);
    }

    /**
     * 通过ID删除数据
     *
     * @param type $delArr 传值模拟 array("tableName" => 值),array("id" => 值)
     * @return type
     */
    public static function del($delArr)
    {
        $tableName = $delArr["tableName"];
        $delId = $delArr["id"];
        $sql = "delete from $tableName where id = $delId";
        return db::runsql($sql);
    }

    /**
     * 通过多个ID删除数据
     *
     * @param type $delArr 传值模拟 array("tableName" => 值),array("id" => 值)
     * @return type
     */
    public static function delByMore($delArr)
    {
        $tableName = $delArr["tableName"];
        $delId = $delArr["delId"];
        $sql = "delete from $tableName where id in ($delId)";
        return db::runsql($sql);
    }

    /**
     * @param $operateArr
     *
     * 添加操作日志
     */
    public static function addOperateLogs($operateArr)
    {
        $saveArr["tableName"] = "lf_logs";
        $saveArr["list"] = $operateArr;
        main::save($saveArr);
    }
}

?>